package com.xckj.teacher.ui.fragment

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.PopupWindow
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.LogUtils
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.LargeValueFormatter
import com.github.mikephil.charting.formatter.ValueFormatter
import com.github.mikephil.charting.utils.ColorTemplate
import com.xckj.teacher.R
import com.xckj.teacher.bean.ClassBean
import com.xckj.teacher.databinding.FragmentClassBinding
import com.xckj.teacher.databinding.FragmentHomeworkBinding
import com.xckj.teacher.framework.BaseFragment
import com.xckj.teacher.iview.IClassView
import com.xckj.teacher.presenter.ClassPresenter
import com.xckj.teacher.ui.activity.ClassDetailActivity
import com.xckj.teacher.ui.activity.EditClassActivity
import com.xckj.teacher.ui.activity.HomeworkReportActivity
import com.xckj.teacher.ui.activity.ProtocolActivity
import com.xckj.teacher.ui.adapter.AccountAdapter
import com.xckj.teacher.ui.adapter.ClassListAdapter
import com.xckj.teacher.util.ActivityMessenger
import com.xckj.teacher.util.get
import com.xckj.teacher.util.startActivity

class HomeWorkFragment(var type: String, var classId: String, var className: String) :
    BaseFragment<FragmentHomeworkBinding>() {

    private val classListAdapter: ClassListAdapter by lazy { ClassListAdapter(arrayListOf()) }
    private val presenter: ClassPresenter by lazy { ClassPresenter(this) }
    var accountPop: PopupWindow? = null


    var selectPosition = 0
    var years = arrayListOf("2023-2024学年", "2022-2023学年", "2021-2022学年")

    //1=听说模考,2=单词跟读,3=课文跟读,4=线上做答
    var typeInt = 1
    var start = ""
    var end = ""

    override fun loadLayout(): Int {
        return R.layout.fragment_homework
    }

    override fun setStatusBarColor(): Int {
        return R.color.white
    }

    inner class ProxyClick {

        fun select() {
            val accountPopView = LayoutInflater.from(this@HomeWorkFragment.activity)
                .inflate(R.layout.account_list_dialog, null)
            accountPop = PopupWindow(
                accountPopView,
                dataBinding?.tvYear?.width ?: 0,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            var rv = accountPopView.findViewById<RecyclerView>(R.id.rv_account)
            var accountAdapter = AccountAdapter(years, selectPosition)
            rv.layoutManager = LinearLayoutManager(this@HomeWorkFragment.activity)
            rv.adapter = accountAdapter

            accountAdapter.setOnItemClickListener { baseQuickAdapter, view, i ->
                accountAdapter.select = i
                selectPosition = i
                accountAdapter.notifyDataSetChanged()
                dataBinding?.tvYear?.text = years[i]
                when (years[i]) {
                    "2023-2024学年" -> {
                        start = "2023"
                        end = "2024"
                    }

                    "2022-2023学年" -> {
                        start = "2022"
                        end = "2023"
                    }

                    "2021-2022学年" -> {
                        start = "2021"
                        end = "2022"
                    }
                }
                updateData()
                accountPop?.dismiss()
            }
            accountPop?.isFocusable = true
            accountPop?.showAsDropDown(dataBinding?.tvYear)
        }

    }

    override fun initData() {
        dataBinding?.click = ProxyClick()

        initLineChart()

        when (type) {
            "听说模考" -> typeInt = 1
            "单词跟读" -> typeInt = 2
            "课文跟读" -> typeInt = 3
            "线上做答" -> typeInt = 4
        }
        start = "2023"
        end = "2024"
        dataBinding?.tvType?.text = "$className ${type}报告"
        updateData()
    }

    fun updateData() {
        presenter.homeWork(start, end, classId, typeInt.toString()) {
            dataBinding?.tvCount?.text = "${it.count}"
            dataBinding?.tvAverage?.text = "${it.average}"
            dataBinding?.tvGoal?.text = "${it.goal}"
            setData(it.linear.goal, it.linear.date)
            dataBinding?.table1?.removeAllViews()
            if (it.list.size != 0) {
                var tabRow1 =
                    View.inflate(this@HomeWorkFragment.activity, R.layout.item_table_row_head, null)
                dataBinding?.table1?.addView(tabRow1)
                it.list.forEach { ll ->
                    var tabRow =
                        View.inflate(this@HomeWorkFragment.activity, R.layout.item_table_row, null)
                    tabRow.findViewById<TextView>(R.id.tv_date).text = ll.date
                    tabRow.findViewById<TextView>(R.id.tv_people).text = "${ll.people}"
                    tabRow.findViewById<TextView>(R.id.tallest).text = "${ll.tallest}"
                    tabRow.findViewById<TextView>(R.id.countScore).text = "${ll.countScore}"
                    tabRow.findViewById<TextView>(R.id.goal).text = ll.goal
                    tabRow.findViewById<TextView>(R.id.average).text = ll.average
                    tabRow.findViewById<TextView>(R.id.lowest).text = "${ll.lowest}"
                    dataBinding?.table1?.addView(tabRow)
                }
            }
        }
    }

    private fun initLineChart() {
        var mChart = dataBinding?.mChart
        mChart?.description?.isEnabled = false
        mChart?.setPinchZoom(true)
        mChart?.isScaleXEnabled = true
        mChart?.isScaleYEnabled = false
        mChart?.setDrawGridBackground(false)

        val l = mChart?.legend
        l?.verticalAlignment = Legend.LegendVerticalAlignment.TOP

        l?.horizontalAlignment = Legend.LegendHorizontalAlignment.LEFT

        l?.orientation = Legend.LegendOrientation.HORIZONTAL
        l?.setDrawInside(false)
        l?.yOffset = 0f
        l?.yEntrySpace = 0f
        l?.textSize = 8f
        l?.form = Legend.LegendForm.LINE
        l?.textColor = Color.parseColor("#FF999999")


        val leftAxis = mChart?.axisLeft
        leftAxis?.valueFormatter = LargeValueFormatter()
        leftAxis?.setDrawGridLines(true)
        leftAxis?.axisLineColor = Color.parseColor("#FFFFFF")
        leftAxis?.gridColor = Color.parseColor("#FFE5E5E5")
        leftAxis?.spaceTop = 35f
        leftAxis?.axisMinimum = 0f // this replaces setStartAtZero(true)
        mChart?.axisRight?.isEnabled = false
        mChart?.isHighlightPerTapEnabled = false
        mChart?.isHighlightPerDragEnabled = false
    }

    private fun setData(yVals1: ArrayList<String>, mLabels: List<String>) {
        val xAxis = dataBinding?.mChart?.xAxis
        xAxis?.granularity = 1f
        xAxis?.setDrawGridLines(false)
        xAxis?.position = XAxis.XAxisPosition.BOTTOM
        xAxis?.setCenterAxisLabels(false)
        xAxis?.axisMinimum = 0f


        var data = arrayListOf<Entry>()
        yVals1.forEachIndexed { i, s ->
            data.add(Entry(i.toFloat(), s.replace("%", "").toFloat()))
        }


        xAxis?.valueFormatter = object : ValueFormatter() {
            override fun getFormattedValue(value: Float): String {
                LogUtils.e(value)
                if (value.toInt() >= 0 && value.toInt() < mLabels.size) {
                    LogUtils.e(mLabels[value.toInt()])
                    return mLabels[value.toInt()]
                }
                return ""
            }
        }
        xAxis?.labelCount = mLabels.size
        val set1: LineDataSet
        if (dataBinding?.mChart?.data != null &&
            dataBinding?.mChart?.data?.getDataSetCount() ?: 0 > 0
        ) {
            set1 = dataBinding?.mChart?.data?.getDataSetByIndex(0) as LineDataSet
            set1.setValues(data)
            dataBinding?.mChart?.data?.notifyDataChanged()
            dataBinding?.mChart?.notifyDataSetChanged()
        } else {
            set1 = LineDataSet(data, "得分率 (%)")
            set1.setCubicIntensity(1.0f)
            set1.axisDependency = YAxis.AxisDependency.LEFT
            set1.setColor(Color.parseColor("#2979FF"))
            set1.setCircleColor(Color.parseColor("#2288FF"))
            set1.setLineWidth(2f)
            set1.circleRadius = 2.5f
            set1.setDrawFilled(true)
            set1.fillAlpha = 54
            set1.setFillColor(ColorTemplate.rgb("#FF79ABFF"))
            set1.setDrawCircleHole(true)
            val lineData = LineData(set1)
            xAxis?.setAxisMinimum(lineData.xMin - 0.5f);
            xAxis?.setAxisMaximum(lineData.xMax + 0.5f);
            dataBinding?.mChart?.setData(lineData)
            dataBinding?.mChart?.invalidate()
        }
    }

}
